
//记录查询出的所有用户信息
var userobj=new Array();

//记录点击当前行的用户ID 修改用户信息使用
var userGridColumnUserId;

function userGridColumnsRenderRolelink(columnUserId,sname){
	userGridColumnUserId=columnUserId;
	showUserRoleForm(columnUserId,sname);
}
function userGridColumnsRenderdellink(columnUserId,sname){
	
	Ext.MessageBox.confirm('信息', '是否确认删除用户： '+sname+'?', function(btn){
		
		if(btn=='yes'){
			Ext.Ajax.request({
				url:'delUser.do',
				method:'POST',
				params:{
					ids:columnUserId
				},
				success:function(response){
					if(response.responseText=='1'){
						Ext.MessageBox.alert('信息','用户删除成功！');
						userGridStore.reload();
					}else{
						Ext.MessageBox.alert('ERROR','用户删除失败！');
					}
				},
				failure:function(){
					Ext.Msg.alert('ERROR','错误');
				}
			});
		}
	});
}
function userGridColumnsRenderInfolink(columnUserId){
	userGridColumnUserId=columnUserId;
	if(userGridColumnUserId==null)
				return ;
	showUserAddForm(2,userobj[columnUserId]);
}

var userRoleform = new Ext.FormPanel({
	    border: false,
	    frame:true,
	    layout:'fit',
	    autoScroll:true,
	    buttons: [{
	        text: '修 改',
	        handler: function() {
	        	
	        	var myt = Ext.getCmp('userRoleCheckboxGroup');
	        	
	        	var sRoles='';
	        	for (var i = 0; i < myt.items.items.length; i++) {
	        		var userRoleckValue=myt.items.items[i];
	        		
	        		if(userRoleckValue.checked){
	        			sRoles+=userRoleckValue.name+',';
	        		}
	        	}
	        	
	        	Ext.Ajax.request({
					url:'saveUserRelRight.do',
					method:'POST',
					params : {
						'nuserId':userGridColumnUserId,
						'sRoles':sRoles
			        }, 
					success: function (response) {
						if(response.responseText=='1'){
							
							Ext.MessageBox.alert('信息!', '成功分配角色!');
			                userRoleWin.hide();
						}else{
							Ext.MessageBox.alert('信息!', '分配角色失败!');
						}
					},
					failure: function (response) {
			            Ext.Msg.alert("Error","错误"); 
			    	}
	        	})
	        }
	    },{
	        text: '返 回',
	        handler: function() {
	        	userRoleWin.hide();
	        }
	    }]
	});
	
	var userRoleWin =new Ext.Window({
	    closeAction:'hide',
	    width: 380,
	    height: 360,
	    autoScroll:true,
	    layout: 'fit',
        resizable: true,
        modal: true,
        items:[userRoleform]
	});
				
function showUserRoleForm(columnUserId,sName) {
	
	if(userRoleWin){
		userRoleWin.setTitle(sName+'-用户角色信息');
	}
	
	 var myt = Ext.getCmp('userRoleCheckboxGroup');
	 
     if(myt){
       userRoleform.remove(myt);
	 }
                	
	Ext.Ajax.request({
		url:'selectUserRelRight.do',
		method:'POST',
		params : {
			nuserId:columnUserId
        }, 
		success: function (response) {
			
			var userRoleArry=Ext.decode(response.responseText);
			
			var userRoleCheckboxArry=new Array();
			for (var i = 0; i < userRoleArry.length; i++) {
				userRoleCheckboxArry.push({name:userRoleArry[i].nRightId,boxLabel: userRoleArry[i].sName, checked: userRoleArry[i].checked==null?false:userRoleArry[i].checked})
			}
			var userRoleCheckboxGroup=new Ext.form.CheckboxGroup({
				id:'userRoleCheckboxGroup',
				columns: 3,
				items:userRoleCheckboxArry
			});
			
			userRoleform.add(userRoleCheckboxGroup);
			userRoleform.doLayout();
			userRoleWin.show();
      	}, 
		failure: function (response) {
            Ext.Msg.alert("Error","错误"); 
    	}
   });
}



var userAddWin;
var userNameField=new Ext.form.TextField({
		labelAlign:'right',
		allowBlank:false,
		fieldLabel: '用户姓名'
});
var usersAccountField=new Ext.form.TextField({
		labelAlign:'right',
		allowBlank:false,
		minLength:5,
		vtype:'alphanum',
		fieldLabel: '用户账号'
});
var usersPasswordField=new Ext.form.TextField({
		labelAlign:'right',
		allowBlank:false,
		fieldLabel: '用户密码',
		inputType:'password'
});
var usersPasswordConfirmField=new Ext.form.TextField({
		labelAlign:'right',
		allowBlank:false,
		fieldLabel: '确认密码',
		inputType:'password'
});
var usernSexField=new Ext.form.ComboBox({
		fieldLabel:'性 别',
		labelAlign:'right',
		id:'usernSexFieldcombox',
		width:80,
        store: new Ext.data.ArrayStore({
            fields: ['value', 'text'],
            data:[
			        [1, '男'],
			        [2, '女'],
			        [3, '未知']
		        ]
        }),
	    valueField:'value',
	    displayField:'text',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        value:1,
        selectOnFocus:true,
        editable:false
});
var usernTypeField=new Ext.form.ComboBox({
		fieldLabel:'用户类型',
		labelAlign:'right',
		editable:false,
		width:80,
        store: new Ext.data.ArrayStore({
            fields: ['value', 'text'],
            data:[
			        [1, '管理人员'],
			        [11, '微信用户']
		        ]
        }),
	    valueField:'value',
	    displayField:'text',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        value:1,
        selectOnFocus:true
});
var usersqqField=new Ext.form.TextField({
		labelAlign:'right',
		fieldLabel: 'QQ'
});
var usersemailField=new Ext.form.TextField({
		labelAlign:'right',
		fieldLabel: '电子邮件',
		vtype:'email'
});
var usersmobileField=new Ext.form.TextField({
		labelAlign:'right',
		fieldLabel: '手 机'
});
var userstelField=new Ext.form.TextField({
		labelAlign:'right',
		fieldLabel: '电 话'
});
var usersfaxField=new Ext.form.TextField({
		labelAlign:'right',
		fieldLabel: '传 真'
});
var userszipField=new Ext.form.TextField({
		labelAlign:'right',
		fieldLabel: '邮 编'
});
var usersaddressField=new Ext.form.TextField({
		labelAlign:'right',
		fieldLabel: '地 址'
});
var usersbriefField=new Ext.form.TextArea({
		labelAlign:'right',
		width:130,
		height:80,
		fieldLabel: '简 介'
});
var usernisValidField=new Ext.form.Checkbox({
		fieldLabel:'是否有效',
		labelAlign:'right',
		checked:true
});

function userVlidate(tinfo){
	if(!userNameField.validate()){
		Ext.Msg.alert('信息','用户姓名不能为空！');
		return false;
	}
	if(!usersAccountField.validate()){
		if(usersAccountField.getValue()==''){
			Ext.Msg.alert('信息','用户账号不能为空！');
		}else{
			Ext.Msg.alert('信息','用户账号最少5位且只能为字母和数字！');
		}
		
		return false;
	}
	if(tinfo==1){
		if(!usersPasswordField.validate()){
			Ext.Msg.alert('信息','用户密码不能为空！');
			return false;
		}
		if(usersPasswordConfirmField.getValue()!=usersPasswordField.getValue()){
			Ext.Msg.alert('ERROR','两次密码不一致！');
			return false;
		}
	}
	
	if(usersemailField.getValue()!=""){
		if(!usersemailField.validate()){
			Ext.Msg.alert('信息','不是有效的邮箱地址！');
			return false;
		}
	}
	return true;
	
}
//tinfo参数值1 :添加 2:修改
function showUserAddForm(tinfo,userJson) {
	
	if(!userAddWin){
		userAddform = new Ext.FormPanel({
		    border: false,
		    labelAlign:'right',
		    frame:true,
		    items: [
		    	userNameField,usersAccountField,usersPasswordField,
		    	usersPasswordConfirmField,usernSexField,usernTypeField,
		    	usersqqField,usersemailField,usersmobileField,userstelField,
		    	usersfaxField,userszipField,usersaddressField,usersbriefField,usernisValidField
		    ],
		    buttons: [{
		        text: tinfo,
		        handler: function() {
		        	if(!userVlidate(tinfo)){
		        		return ;
		        	}
		        	if(this.text=='添 加'){
	        			Ext.Ajax.request({
							url:'saveUser.do',
							method:'POST',
							params : {
								sAccount:usersAccountField.getValue(),
								sPassword:usersPasswordField.getValue(),
			                   	sName : userNameField.getValue(),
			                   	nType:usernTypeField.getValue()==""?1:usernTypeField.getValue(),
			                   	nSex:usernSexField.getValue()==""?1:usernSexField.getValue(),
			                   	sQQ:usersqqField.getValue(),
			                   	sEmail:usersemailField.getValue(),
			                   	sMobile:usersmobileField.getValue(),
			                   	sTel:userstelField.getValue(),
			                   	sFax:usersfaxField.getValue(),
			                   	sZip:userszipField.getValue(),
			                   	sAddress:usersaddressField.getValue(),
			                   	sBrief:usersbriefField.getValue(),
			                   	nisValid:usernisValidField.checked?1:2
			                }, 
			  				success: function (response) {

			  					if(response.responseText=='-1'){
			                       Ext.MessageBox.alert('Error', '用户账号已存在，请重新输入!');
			  					}else if(response.responseText=='1'){
			  						Ext.MessageBox.alert('信息!', '用户添加成功!');
			                        userAddform.getForm().reset();
			                        userAddWin.hide();
			                        userGridStore.reload();
			  					}
			  					else{
			  						Ext.Msg.alert("Error","用户添加失败！"); 
			  					}
			              	}, 
			  				failure: function (response) {
			                    Ext.Msg.alert("Error","错误"); 
			            	}
					   });
		        	}else if(this.text=='修 改'){
		        		if(usersPasswordConfirmField.getValue()!=usersPasswordField.getValue()){
							Ext.Msg.alert('ERROR','两次密码不一致！');
							return false;
						}
		        		Ext.Ajax.request({
							url:'upUser.do',
							method:'POST',
							params : {
								sAccount:usersAccountField.getValue(),
								spassword:usersPasswordField.getValue(),
			                   	sName : userNameField.getValue(),
			                   	nType:usernTypeField.getValue()==""?1:usernTypeField.getValue(),
			                   	nSex:usernSexField.getValue()==""?1:usernSexField.getValue(),
			                   	sQQ:usersqqField.getValue(),
			                   	sEmail:usersemailField.getValue(),
			                   	sMobile:usersmobileField.getValue(),
			                   	sTel:userstelField.getValue(),
			                   	sFax:usersfaxField.getValue(),
			                   	sZip:userszipField.getValue(),
			                   	sAddress:usersaddressField.getValue(),
			                   	sBrief:usersbriefField.getValue(),
			                   	nisValid:usernisValidField.checked?1:2,
			                   	nuserId:userGridColumnUserId
			                }, 
			  				success: function (response) {
			  					if(response.responseText=='1'){
			  						Ext.MessageBox.alert('信息!', '用户修改成功!');
			                        userAddform.getForm().reset();
			                        userAddWin.hide();
			                        userGridStore.reload();
			  					}
			  					else{
			  						Ext.Msg.alert("Error","用户修改失败！"); 
			  					}
			              	}, 
			  				failure: function (response) {
			                    Ext.Msg.alert("Error","错误"); 
			            	}
					   });
		        	}
		        	
		        }
		    },{
		        text: '返 回',
		        handler: function() {
		        	userAddform.getForm().reset();
		        	userAddWin.hide();
		        }
		    }]
		});
		
		userAddWin =new Ext.Window({
		    title: '用户信息',
		    closeAction: 'hide',
		    width: 300,
		    height: 520,
		    layout: 'fit',
	        resizable: true,
	        modal: true,
	        items: userAddform,
	        listeners :{
	        	close:function(){
	        		userAddform.getForm().reset();
	        	}
	    	}
		});
	}
    userAddWin.show();
    
    if(tinfo==2){
    	userAddWin.setTitle('用户信息：'+userJson.sname);
    	userAddform.buttons[0].setText('修 改');
    	if(userJson.sname!=null)
    		userNameField.setValue(userJson.sname);
    	if(userJson.saccount!=null)
    		usersAccountField.setValue(userJson.saccount);
    	if(userJson.nsex!=null)
    		usernSexField.setValue(userJson.nsex);
    	if(userJson.ntype!=null)
    		usernTypeField.setValue(userJson.ntype);
    	if(userJson.sqq!=null)
    		usersqqField.setValue(userJson.sqq);
    	if(userJson.semail!=null)
    		usersemailField.setValue(userJson.semail);
    	if(userJson.smobile!=null)
    		usersmobileField.setValue(userJson.smobile);
    	if(userJson.stel!=null)
    		userstelField.setValue(userJson.stel);
    	if(userJson.sfax!=null)
    		usersfaxField.setValue(userJson.sfax);
    	if(userJson.szip!=null)
    		userszipField.setValue(userJson.szip);
    	if(userJson.saddress!=null)
    		usersaddressField.setValue(userJson.saddress);
    	if(userJson.sbrief!=null)
    		usersbriefField.setValue(userJson.sbrief);
    	if(userJson.nisValid!=null)
    		usernisValidField.setValue(userJson.nisValid==1?true:false);
    	usersPasswordField.allowBlank=true;
    	usersPasswordConfirmField.allowBlank=true;
	}else{
		userAddform.buttons[0].setText('添 加');
		userAddform.getForm().reset();
		usersPasswordField.allowBlank=false;
    	usersPasswordConfirmField.allowBlank=false;
	}
}

Ext.onReady(function(){
	useriswriteidb= Ext.get('useriswriteid').getValue()==1?true:false;
	
	var userNameSearchField=new Ext.form.TextField({
		fieldLabel:'用户名称',
		labelAlign:'right'
	});
	
	var userClassSearchField=new Ext.form.ComboBox({
		fieldLabel:'用户类型',
		labelAlign:'right',
		width:100,
        store: new Ext.data.ArrayStore({
            fields: ['value', 'text'],
            data:[
			        [1, '管理人员'],
			        [11, '微信用户']
		    ]
        }),
	    valueField:'value',
	    displayField:'text',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        emptyText:'全部',
        selectOnFocus:true
	});
	
	var userSearchBtn=new Ext.Button({
		text:'查询',
		handler:function(){
			
			userGridStore.load({
				params : {
					start : 0,
					limit : 20,
					'sName':userNameSearchField.getValue(),
					'nType':userClassSearchField.getValue()==""?0:userClassSearchField.getValue()
				}
			});
		}
	});
	
	var userSearch=new Ext.Panel({
		height:50,
		region:'north',
		layout:'column',
		frame: true,
		border:false,
		bodyBorder:false,
		items:[
			{columnWidth:.3,layout:'form',labelAlign:'right',items:[userNameSearchField]},
			{columnWidth:.4,layout:'form',labelAlign:'right',items:[userClassSearchField]},
			{columnWidth:.3,items:[userSearchBtn]}]		
	});
	
	 userGridStore = new Ext.data.Store({
        autoLoad: false,
        proxy : new Ext.data.HttpProxy({
            url: 'searchUser.do'
        }),
        baseParams:{
        	'sName':userNameSearchField.getValue(),
			'nType':userClassSearchField.getValue()==""?0:userClassSearchField.getValue()
        },
        reader:new Ext.data.JsonReader({
             totalProperty: 'totalSize',
             root:'list'
        },[
            {name: 'nuserId',mapping:'nuserId', type: 'int'},
        	{name: 'ntype',mapping:'ntype',   type: 'int'},
        	{name: 'saccount',mapping:'saccount', type: 'string'},
        	{name: 'sname',mapping:'sname', type: 'string'},
        	{name: 'nsex',mapping:'nsex', type: 'int'},
        	{name: 'dcreateTime',mapping:'dcreateTime', type: 'date',
        		convert : function(v) {
        			return new Date(v);
        		}
        	},
        	{name: 'nisValid',mapping:'nisValid', type: 'int'}        	
        ])
    });
    
    userGridStore.on("beforeload", function(thiz, options) { 
		thiz.baseParams["sName"] = userNameSearchField.getValue(); 
		thiz.baseParams["nType"] = userClassSearchField.getValue()==""?0:userClassSearchField.getValue();
	});
    
    userAddBtn =new Ext.Button({
		text:'添加用户',
		hidden:useriswriteidb,
		handler:function(){
			showUserAddForm(1,'');
		}
	});
    
    var userGridBar=new Ext.PagingToolbar({
		store: userGridStore,
		displayInfo: true,
		pageSize:20,
		displayMsg : '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
		emptyMsg: "没有记录可以显示",
		beforePageText:'当前页码',
		afterPageText:'共{0}页', 
		firstText:'第一页', 
		prevText:'上一页', 
		nextText:'下一页', 
		lastText:'最后一页', 
		refreshText:'刷新当前页',
		items:['-', userAddBtn]
     });
     
    userGridColumnsRenderInfo=function(value, cellmeta, record, rowIndex, columnIndex, store){
    	userobj[record.data.nuserId]=record.json;
    	var linkhtml='';
    	if(useriswriteidb==false){
    		linkhtml='<a onclick="userGridColumnsRenderInfolink('+record.data.nuserId+')" href="javascript:void(0)">详细 </a>';
	    	linkhtml+='<a style="margin-left:20px;margin-right:20px" onclick="userGridColumnsRenderRolelink('+record.data.nuserId+',\''+record.data.sname+'\')" href="javascript:void(0)">分配角色</a>';
	    	linkhtml+='<a onclick="userGridColumnsRenderdellink('+record.data.nuserId+',\''+record.data.sname+'\')" href="javascript:void(0)"> 删除</a>';

    	}
	    	return linkhtml;
	};
	
	userGrid = new Ext.grid.GridPanel({
        store: userGridStore,
        region:'center',
		disableSelection: true,
		border:false,
		frame:true,
		stripeRows:true,
		loadMask :{msg:"数据加载中，请稍等..."},
		layout:'fit',
		viewConfig:{
			forceFit: true,
			scrollOffset:0
		},
        cm:new Ext.grid.ColumnModel([
        	new Ext.grid.RowNumberer(),
            {header: "用户标识", width:50, dataIndex: 'nuserId', sortable: true},
            {header: "用户账号", flex: 1, dataIndex: 'saccount', sortable: true},
            {header: "用户姓名",flex: 1, dataIndex: 'sname', sortable: true},
            {header: "用户类型", width:80, dataIndex: 'ntype', sortable: true,
            	renderer:function(value){
            		if(value == 1){
            			return '管理人员';
            		}else if(value == 11){
            			return '微信用户';
            		}else {
            			return '未知';
            		}            		
            	}
            },
            {header: "用户性别", width:50,sortable: true,dataIndex: 'nsex',
            	renderer:function(value){
            		if (value == 1) {
			            return '男';
			        }else if(value ==2){
			        	return '女';
			        }else{
			        	return '未知';
			        }
            	}
            },
            {header: "是否有效", width:50,sortable: true,dataIndex: 'nisValid',
            	renderer:function(value){
            		if (value == 1) {
			            return '有效';
			        }else{
			        	return '无效';
			        }
            	}
            },
            {header: "创建时间",flex: 1, dataIndex: 'dcreateTime', sortable: true,renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s')},
            {header: "操作", width:150,align:'center',sortable: true,renderer:userGridColumnsRenderInfo}
        ]),
        bbar: userGridBar
    });
    
	 var mainPanel = new Ext.Viewport({
	 	layout:'border',
		renderTo:'userDIV',
		id:'userMainPanel',
		items:[userSearch,userGrid],
		listeners: {
	        'resize': function(viewport,adjWidth,adjHeight,rawWidth,rawHeight)  {
	          	Ext.getCmp("userMainPanel").setHeight((document.body.clientHeight - 290) * 0.67);  
			}
    	}
	});
	
})